package com.itsitio.registeradmin.web.controller;

import java.util.List;

import org.apache.commons.collections.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.itsitio.registeradmin.dto.UserDTO;
import com.itsitio.registeradmin.enums.RegistrationStatus;
import com.itsitio.registeradmin.model.Branch;
import com.itsitio.registeradmin.model.MilesDetail;
import com.itsitio.registeradmin.model.News;
import com.itsitio.registeradmin.model.Portal;
import com.itsitio.registeradmin.model.User;
import com.itsitio.registeradmin.model.UserRegistration;
import com.itsitio.registeradmin.service.BranchSrv;
import com.itsitio.registeradmin.service.CompanyDepartmentSrv;
import com.itsitio.registeradmin.service.CompanyPositionSrv;
import com.itsitio.registeradmin.service.NewsSrv;
import com.itsitio.registeradmin.service.PortalSrv;
import com.itsitio.registeradmin.service.UserRegistrationSrv;
import com.itsitio.registeradmin.service.UserSrv;
import com.itsitio.registeradmin.web.UserContext;

@Controller
@SessionAttributes({"userContext"})
public class UserController extends BaseController{
	
	@Autowired
	private UserRegistrationSrv userRegSrv;
	
	@Autowired
	private UserSrv userSrv;
	
	@Autowired
	private CompanyPositionSrv positionSrv;
	
	@Autowired
	private CompanyDepartmentSrv departmentSrv;
	
	@Autowired
	private PortalSrv portalSrv;
	
	@Autowired
	private NewsSrv newsSrv;
	
	@Autowired
	private BranchSrv branchSrv;

	/**
	 * Muestra la pantalla de Usuario: 
	 * - formulario cargado con los datos que el usuario que cargo al momento de registrarse
	 * - lista de empresas que tienen nombre parecido 
	 * a la que cargo el usuario y/o cuil = al cargado por el usuario. 
	 * @param model
	 * @param userRegId
	 * @return
	 */
	@RequestMapping("/showUserSection.html")
	public String showUserSection(Model model, @RequestParam(required=true) Integer userRegId, @RequestParam(required=true) Integer branchId,
			@ModelAttribute UserContext userContext) {
		System.out.println("===== UserController.showUserSection() - userRegId="+userRegId+", branchId="+branchId);
		
		//buscamos los usuarios que pertenecen a la surcursal, por el id de la sucursal
		List<User> userList = userSrv.getUserListByBranchId(branchId);
		createModelForView(model, userRegId, branchId, userList);

		
		if (userList != null) {
			System.out.println("===== UserController.showUserSection() - userList.size="+userList.size());
		} else {
			System.out.println("===== UserController.showUserSection() - userList is NULLLLL");		
		}
		
		// bread crumbs
		Branch branch = branchSrv.obtener(branchId);
		userContext.setBranchAddress(branch.getAddress());
		userContext.setCity(branch.getCity());
		userContext.setProvince(branch.getProvince() != null ? branch.getProvince().getName() : "");
		userContext.setPhone(branch.getPhone());
		
		return forward( "user/userSection", model);
	}

	private void createModelForView(Model model, Integer userRegId, Integer branchId, List<User> userList) {
		UserDTO userDTO = new UserDTO();
		
		UserRegistration userRegistration = userRegSrv.get(userRegId);
		
		//carga el formulario de nueva empresa
		if(userRegistration != null){
			userDTO.setFirstName(userRegistration.getUserFirstName());
			userDTO.setLastName(userRegistration.getUserLastName());
			userDTO.setEmail(userRegistration.getUserEmail());
			
			if (userRegistration.getCompanyDepartment() != null){
				userDTO.setCompanyDepartment(userRegistration.getCompanyDepartment().getNameEs());
				userDTO.setCompanyDepartmentId(userRegistration.getCompanyDepartment().getId());
			} else {
				userDTO.setCompanyDepartment("");				
			}
			
			if (userRegistration.getCompanyPosition() != null){
				userDTO.setCompanyPosition(userRegistration.getCompanyPosition().getNameEs());
				userDTO.setCompanyPositionId(userRegistration.getCompanyPosition().getId());
			} else {
				userDTO.setCompanyPosition("");
			}	
			userDTO.setPhone(userRegistration.getUserPhone());
			userDTO.setStatus(userRegistration.getStatus());
			
		}

	    
		model.addAttribute("newUser", userDTO);
		model.addAttribute("userList", userList);
		model.addAttribute("positionList", positionSrv.getPositionList());
		model.addAttribute("departmentList", departmentSrv.getDepartmentList());
		model.addAttribute("branchId", branchId);
		model.addAttribute("userRegId", userRegId);
		model.addAttribute("statusList", RegistrationStatus.getStatusListForUserRegistrationUpdate());
	}

	@RequestMapping("/filterUser.html")
	public String filterUserRegistration(Model model, @RequestParam(required=true) Integer userRegId, 
			@RequestParam(required=true) Integer branchId,
			@RequestParam(required=false) String userLastName,			
			@RequestParam(required=false) String userEmail){
		System.out.println("===== UserController.showUserSection() - userRegId="+userRegId);
		System.out.println("===== UserController.showUserSection() - branchId="+branchId);
		System.out.println("===== UserController.showUserSection() - userLastName="+userLastName);
		System.out.println("===== UserController.showUserSection() - userEmail="+userEmail);

		//buscamos los usuarios (todos) los que conciden parcialmente el apellido y/o email
		List<User> userList = userSrv.findUserByFilter(userLastName, userEmail);
		
		createModelForView(model, userRegId, branchId, userList);
		
		model.addAttribute("userLastName", userLastName);
		model.addAttribute("userEmail", userEmail);
		
		return forward( "user/userSection", model);
	}
	
	/**
	 * @param model
	 * @param action
	 * @return
	 */
	@RequestMapping("/updateUser.html")
	public String updateUser(Model model, @RequestParam String nextStep,
			@RequestParam Integer userRegId, @RequestParam Integer branchId,@RequestParam Integer selectedUser,
			@RequestParam String name, @RequestParam String lastName, @RequestParam String email, 
			@RequestParam Integer userCompanyPosition2, @RequestParam Integer userCompanyDepartment2, 
			@RequestParam String phone, @ModelAttribute UserContext userContext,
			@RequestParam String status2) {		
		
		User user = null;
		
		Integer userId = selectedUser;
		if(nextStep.equalsIgnoreCase("actualizar")){
			
			user = userSrv.updateUserWithUserRegistrationData(selectedUser, branchId,
					name, lastName, email,userCompanyPosition2, userCompanyDepartment2, phone);
			
		} else if (nextStep.equalsIgnoreCase("nuevoUsuario")){
			
			user = userSrv.createUserFromUserRegistration(branchId,
					name, lastName, email,userCompanyPosition2, userCompanyDepartment2, phone);
			
			//como el user es nuev, tenemos que obtener el id del nuevo user.
			userId = user.getId();			
		} else{
			user = userSrv.obtener(userId);
		}
		
		model.addAttribute("userId", userId);
		model.addAttribute("branchId", branchId);
//		model.addAttribute("user", user);
		
		//tab portales del usuario
//		List<Portal> allPortals = portalSrv.findAllPortals();
//		List<Portal> userPortals = userSrv.getUserPortals(user);
//		model.addAttribute("userPortalList", userPortals);
//		model.addAttribute("portalList", ListUtils.subtract(allPortals, userPortals) );
		
		//tab news del usuario
//		List<News> allNews = newsSrv.findAllNews();
//		List<News> userNews = userSrv.getUserNews(user);
//		model.addAttribute("userNewsList", userNews);
//		model.addAttribute("newsList", ListUtils.subtract(allNews, userNews) );
		
		model.addAttribute("activeTab", 0);
		
//		return forward( "user/userInfoAdmin", model);
		
		// bread crumbs
		userContext.setUserRegFirstname(user.getFirstName());
		userContext.setUserRegLastname(user.getLastName());
		userContext.setUserRegMail(user.getEmail());
		
		//actualiza el user registration
		UserRegistration userRegistration = userRegSrv.updateUserRegistrationStatus(userRegId, status2);
		
		return returnToTabs(user, model);
	}
	
	@RequestMapping("/updateUserPortales.html")
	public String updateUserPortales(Model model, 
			@RequestParam Integer userId,
			@RequestParam(required=false) Integer[] selectedPortals,
			@RequestParam Integer activeTab) {	
		User user = userSrv.obtener(userId);
		userSrv.updateUserPortals(selectedPortals, user);
		model.addAttribute("activeTab", activeTab);
		return returnToTabs(user, model);
	}
	
	
	@RequestMapping("/updateUserNews.html")
	public String updateUserNews(Model model, 
			@RequestParam Integer userId,
			@RequestParam(required=false) Integer[] selectedNews,
			@RequestParam Integer activeTab) {	
		User user = userSrv.obtener(userId);
		userSrv.updateUserNews(selectedNews, user);
		model.addAttribute("activeTab", activeTab);
		return returnToTabs(user, model);
	}
	
	public String returnToTabs(User user, Model model){
		model.addAttribute("user", user);
		
		//tab portales del usuario
		List<Portal> allPortals = portalSrv.findAllPortals();
		List<Portal> userPortals = userSrv.getUserPortals(user);
		List<Portal> portalList = userPortals != null && !userPortals.isEmpty()? ListUtils.subtract(allPortals, userPortals) : allPortals ;
		model.addAttribute("userPortalList", userPortals);
		model.addAttribute("portalList", portalList );
		
		//tab news del usuario
		List<News> allNews = newsSrv.findAllNews();
		List<News> userNews = userSrv.getUserNews(user);
		List<Portal> newsList = userNews != null && !userNews.isEmpty()? ListUtils.subtract(allNews, userNews) : allNews ;
		model.addAttribute("userNewsList", userNews);
		model.addAttribute("newsList", newsList );
		
		//tab millas detallado del usuario
		List<MilesDetail> milesDetail = userSrv.getUserMilesDetail(user);
		model.addAttribute("milesDetail", milesDetail);
		
		return forward("user/userInfoAdmin", model);
	}
	
	@RequestMapping("/showUserPortalsDetail.html")
	public String showUserPortalsDetail(Model model, 
			@RequestParam Integer userId) {	
		User user = userSrv.obtener(userId);
		List<Portal> userPortals = userSrv.getUserPortals(user);
		model.addAttribute("userPortals", userPortals);
		return "user/userPortalDetails";
	}
	
	@RequestMapping("/showUserNewsDetail.html")
	public String showUserNewsDetail(Model model, 
			@RequestParam Integer userId) {	
		User user = userSrv.obtener(userId);
		List<News> userNews = userSrv.getUserNews(user);
		model.addAttribute("userNews", userNews);
		return "user/userNewsDetails";
	}
	
	@RequestMapping("/showUserMilesDetail.html")
	public String showUserMilesDetail(Model model, 
			@RequestParam Integer userId) {	
		User user = userSrv.obtener(userId);
		List<MilesDetail> userMiles = userSrv.getUserMilesDetail(user);
		model.addAttribute("userMiles", userMiles);
		return "user/userMilesDetails";
	}
}
